import axios from 'axios'

class Request {
  constructor(props) {
    this.init(props)
  }
  init(props) {
    let servicesParams = {
      baseURL: props && props.baseURL ? props.baseURL : import.meta.env.VITE_APP_BASE_API,
      timeout: props && props.timeout ? props.timeout : 15000,
      headers: {
        'Content-Type': 'application/json;charset=utf-8',
        'X-MOCK-USER': process.env.NODE_ENV === 'development' ? true : false, // 测试使用代码，用于使用测试登录用户
      },
      withCredentials: true, // 跨域携带cookie
      validateStatus: function (status) {
        return status >= 200 && status < 300 // 默认的
      },
    }

    // 添加取消请求功能
    const CancelToken = axios.CancelToken
    this.cancelTokenSource = CancelToken.source()

    // 创建axios实例
    const service = axios.create(servicesParams)
    service.interceptors.request.use(
      function (config) {
        // 添加全局Loading（需要先引入Loading组件）
        // Loading.show()

        // 添加认证Token
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }

        return config
      },
      function (request) {
        return request
      },
      function (error) {
        return Promise.reject(error)
      },
    )
    service.interceptors.response.use(
      (response) => {
        // Loading.hide()

        // 根据后端数据结构调整
        const { data, code, message } = response.data

        if (code === 200) {
          return data
        } else {
          // 统一错误提示
          ElMessage.error(message || 'Error')
          return Promise.reject(new Error(message || 'Error'))
        }
      },
      (error) => {
        // Loading.hide()

        // HTTP状态码处理
        if (error.response) {
          switch (error.response.status) {
            case 401:
              // 跳转登录页
              break
            case 403:
              // 权限不足提示
              break
            case 500:
              // 服务器错误
              break
          }
        }
        return Promise.reject(error)
      },
    )
    this.service = service
  }
}
class RequestInit extends Request {
  init(props) {
    super.init(props)
    return this.service
  }
}
const request = new Request().service
const requestInit = new RequestInit()
export default request
export { request, requestInit, Request } // 导出类便于扩展
